use axum::{extract::State, routing::get, Json, Router};
use lib_core::model::{
    user::{UserBmc, UserForLogin},
    ModelManager,
};
use lib_web::{error::Result, middleware::mw_auth::CtxW};
use serde_json::{json, Value};

// Axum router for '/api/user-context'
pub fn routes(mm: ModelManager) -> Router {
    Router::new()
        .route("/user-context", get(api_user_handler))
        .with_state(mm)
}

async fn api_user_handler(
    State(_mm): State<ModelManager>,
    ctx: Option<CtxW>,
) -> Result<Json<Value>> {
    let ctx = ctx.map(|ctx| ctx.0);
    match ctx {
        Some(ctx) => {
            let user_id = ctx.user_id();
            let user: UserForLogin = UserBmc::get(&ctx, &_mm, user_id).await?;
            let user_id = user.id;
            // Create the success body.
            let body = Json(json!({
                "result": {
                    "user": {
                        "id": user_id,
                        "username": user.username
                    }
                },
                 "success":true

            }));

            Ok(body)
        }
        None => Ok(Json(json!({
            "result": {
            }
        }))),
    }
}
